<template>
  <div class="chart" ref="baseEchartRef" :style="{ ...echartStyle }"></div>
</template>

<script setup>
import * as echarts from "echarts/core";
import { computed, ref, watch, onMounted } from "vue";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";

echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  CanvasRenderer,
  PieChart,
]);

const props = defineProps({
  height: { type: String, default: "300px" },
  pieDate: { type: Array, default: () => [] },
});

const baseEchartRef = ref(null);
let baseChart = null;

const echartStyle = computed(() => {
  return {
    width: "100%",
    height: props.height,
  };
});

const initChart = () => {
  if (!baseChart) {
    baseChart = echarts.init(baseEchartRef.value);
  }
  baseChart.setOption({
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b} : {c} ({d}%)",
    },
    legend: {
      orient: "vertical",
      left: "left",
      data: props.pieDate.map((item) => item.name),
    },
    series: [
      {
        name: "资产分布",
        type: "pie",
        radius: "50%",
        data: props.pieDate,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  });
};

onMounted(() => {
  initChart();
});

watch(() => props.pieDate, () => {
  initChart();
});
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>